package com.example.demo.controller;



import ch.qos.logback.classic.Logger;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.Utils.JwtUtils;
import com.example.demo.common.Result;
import com.example.demo.entity.Department;
import com.example.demo.entity.Restaurant;
import com.example.demo.entity.User;
import com.example.demo.service.DepartmentService;
import com.example.demo.service.RestaurantService;
import com.example.demo.service.UserService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/restaurants")
public class RestaurantController {
    ch.qos.logback.classic.Logger logger = (Logger) LoggerFactory.getLogger(RestaurantController.class);
    @Autowired
    private RestaurantService restaurantService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;
    @GetMapping
    public List<Restaurant> getAllRestaurants(@RequestHeader("Authorization") String authHeader) {
//        logger.info("getAllRestaurants");
//        logger.info(authHeader);
        String token = authHeader.replace("Bearer ", "");

        if (!jwtUtils.validateToken(token)) {
            throw new RuntimeException("Invalid token");
        }
        String username = jwtUtils.getUsernameFromToken(token);
        if (userService.isAdmin(username)) {
            return restaurantService.list();
        }
        // 假设餐厅表中有user_id字段关联用户
        int userId = userService.getOne(new QueryWrapper<User>().eq("username", username)).getId();
        QueryWrapper<Restaurant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return restaurantService.list(queryWrapper);
    }



    @PostMapping
    public ResponseEntity<Map<String, Object>> addRestaurant(
            @RequestHeader("Authorization") String token,
            @RequestBody Restaurant restaurant
    ) {
        Map<String, Object> response = new HashMap<>();
        try {
            Integer userId = jwtUtils.getUserIdFromToken(token.replace("Bearer ", ""));
            restaurant.setUserId(userId);

            boolean isSaved = restaurantService.save(restaurant);
            if (isSaved) {
                // 使用Java 8兼容方式构建响应
                Map<String, Object> data = new HashMap<>();
                data.put("id", restaurant.getId());
                data.put("name", restaurant.getName());
                data.put("userId", restaurant.getUserId());

                return ResponseEntity.ok(new HashMap<String, Object>() {{
                    put("success", true);
                    put("code", 200);
                    put("data", data);
                }});
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(new HashMap<String, Object>() {{
                put("success", false);
                put("code", 400);
                put("message", "创建失败: " + e.getMessage());
            }});
        }
        return ResponseEntity.internalServerError().build();
    }
    @GetMapping("/search")
    public List<Restaurant> searchRestaurants(@RequestHeader("Authorization") String token, @RequestParam String name) {
        if (!jwtUtils.validateToken(token)) {
            throw new RuntimeException("Invalid token");
        }
        QueryWrapper<Restaurant> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        return restaurantService.list(queryWrapper);
    }

    @PutMapping("/{id}")
    public Result<?> updateRestaurant(
            @RequestHeader("Authorization") String token,
            @PathVariable Integer id,
            @RequestBody Restaurant restaurant) {

        if (!jwtUtils.validateToken(token.replace("Bearer ", ""))) {
            return Result.error(401, "无效的Token");
        }

        // 权限验证：只能修改自己的餐厅
        Integer userId = jwtUtils.getUserIdFromToken(token);
        Restaurant existing = restaurantService.getById(id);
        if (existing == null || !existing.getUserId().equals(userId)) {
            return Result.error(403, "无权限修改该餐厅");
        }

        restaurant.setId(id);
        return restaurantService.updateById(restaurant)
                ? Result.success()
                : Result.error(500, "更新失败");
    }

}